package com.example.photo.utils;

import cn.hutool.core.date.DateUtil;
import com.example.photo.model.VO.UserVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lwh
 * @time 2023/03/26 14:48
 */
@Slf4j
public class JwtTokenUtils {
    public static final String TOKEN_HEADER = "Token";

    public static final String ROLE_HEADER = "Role";

    public static final String USERID_HEADER = "UserId";

    // 用户id
    private static final String CLAIM_KEY_USER_ID = "userId";

    // 用户名称
    private static final String CLAIM_KEY_USERNAME = Claims.SUBJECT;

    // 创建时间
    private static final String CLAIM_KEY_CREATED = "created";

    // 用户身份
    private static final String CLAIM_KEY_ROLE = "role";

    // 过期时间3600秒（1个小时）
    private static final long EXPIRATION = 3600 * 24L;

    // 选择了记住我之后的过期时间为7天
    private static final long EXPIRATION_REMEMBER = 604800L;

    // 每次刷新Token的时间间隔，默认30分钟
    public static final int INTERVAL_PER_REFRESH = 30 * 60;

    // 密钥
    private static final String SECRET = "news_photo";


    /**
     * 根据用户信息生成token
     */
    public static String generateToken(UserVO userVO, boolean isRememberMe) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USER_ID, userVO.getUserId());
        claims.put(CLAIM_KEY_USERNAME, userVO.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_ROLE, userVO.getIsAdmin());
        return generateToken(claims, isRememberMe);
    }

    public static String generateToken(UserVO userVO) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USER_ID, userVO.getUserId());
        claims.put(CLAIM_KEY_USERNAME, userVO.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_ROLE, userVO.getIsAdmin());
        return generateToken(claims, false);
    }

    /**
     * 从数据声明生成令牌
     */
    private static String generateToken(Map<String, Object> claims, boolean isRememberMe) {
        long exp = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        Date expirationDate = new Date(System.currentTimeMillis() + exp * 1000);
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 获取Token中的主体
     */
    private static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("JWT格式验证失败: {}", token);
        }
        return claims;
    }

    /**
     * 从token中获取用户身份
     */
    public static Integer getUserRoleFromToken(String token) {
        Integer username = null;
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            username = (Integer) claims.get(CLAIM_KEY_ROLE);
        }
        return username;
    }

    /**
     * 从token种获取用户id
     */
    public static Integer getUserIdFromToken(String token) {
        Integer userId = null;
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            userId = (Integer) claims.get(CLAIM_KEY_USER_ID);
        }
        return userId;
    }

    /**
     * 判断token是否已经失效
     */
    public static boolean isTokenExpired(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            Date expiredDate = claims.getExpiration();
            if (expiredDate != null) {
                return expiredDate.before(new Date());
            }
        }
        return true;
    }

    /**
     * 当原来的token没过期时是可以刷新的
     */
    public static String refreshToken(String oldToken) {
        if (StringUtils.isEmpty(oldToken)) {
            return null;
        }
        //token校验不通过
        Claims claims = getClaimsFromToken(oldToken);
        if (claims == null) {
            return null;
        }
        //如果token已经过期，不支持刷新
        if (isTokenExpired(oldToken)) {
            return null;
        }
        //如果token在30分钟之内刚刷新过，返回原token
        if (tokenRefreshJustBefore(oldToken)) {
            return oldToken;
        } else {
            claims.put(CLAIM_KEY_CREATED, new Date());
            return generateToken(claims, false);
        }
    }

    /**
     * 判断token在指定时间内是否刚刚刷新过
     *
     * @param token 原token
     */
    private static boolean tokenRefreshJustBefore(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims == null) {
            return false;
        }
        Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
        Date refreshDate = new Date();
        //刷新时间在创建时间的指定时间内
        return refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, JwtTokenUtils.INTERVAL_PER_REFRESH));
    }

}
